package p11.code;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Memoizer2<A,V> implements Computable<A,V> {


    private final Map<A,V> cache = new ConcurrentHashMap<>();

    private final Computable<A,V> c;

    public Memoizer2(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException {
        V result = cache.get(arg);//首先在hashmap中查找键arg对应的值
        if(result == null){//如果没有对应的值
            result=c.compute(arg);//计算之
            cache.put(arg,result);//将其存入hashmap中
        }
        return result;//返回值
    }

}
